"""脑波数据模型

定义脑波数据的数据库模型和相关操作
支持会话级别的脑波数据存储，一个会话对应一条记录
使用Peewee ORM进行数据库操作，各频段数据以JSON格式累积存储
"""

import json
from datetime import datetime
from typing import Optional, Dict, Any
from peewee import *

from app.core.database import BaseModel


class BrainWave(BaseModel):
    """脑波数据模型
    
    存储脑波监测会话的基本信息和各频段数据
    一个会话ID对应一条记录，数据以累积方式存储
    """
    
    # 基本信息
    id = AutoField(primary_key=True, help_text="会话ID")
    room_id = CharField(max_length=36, null=False, help_text="所属房间ID")
    user_id = CharField(max_length=50, null=True, help_text="用户ID（可选）")
    
    # 时间信息
    start_time = DateTimeField(null=False, help_text="会话开始时间")
    end_time = DateTimeField(null=False, help_text="会话结束时间")
    total_seconds = IntegerField(null=False, help_text="会话时长（秒）")
    updated_at = DateTimeField(default=datetime.now, help_text="记录更新时间")
    
    # 各频段脑波数据，存储为JSON格式
    eeg_wave_data = TextField(null=True, help_text="原始脑波数据")
    delta_data = TextField(null=True, help_text="Delta波段数据(0.5-4Hz)")
    theta_data = TextField(null=True, help_text="Theta波段数据(4-8Hz)")
    low_alpha_data = TextField(null=True, help_text="低Alpha波段数据(8-10Hz)")
    high_alpha_data = TextField(null=True, help_text="高Alpha波段数据(10-12Hz)")
    low_beta_data = TextField(null=True, help_text="低Beta波段数据(12-20Hz)")
    high_beta_data = TextField(null=True, help_text="高Beta波段数据(20-30Hz)")
    low_gamma_data = TextField(null=True, help_text="低Gamma波段数据(30-40Hz)")
    mid_gamma_data = TextField(null=True, help_text="中Gamma波段数据(40-50Hz)")
    
    class Meta:
        table_name = 'brain_wave'
        indexes = (
            (('room_id',), False),
            (('user_id',), False),
        )
    
    @classmethod
    def create_session(cls, room_id: str, user_id: str = None) -> 'BrainWave':
        """创建新的脑波监测会话
        
        Args:
            room_id: 房间ID
            user_id: 用户ID（可选）
            
        Returns:
            BrainWave: 创建的会话实例
        """
        now = datetime.now()
        return cls.create(
            room_id=room_id,
            user_id=user_id,
            start_time=now,
            end_time=now,
            total_seconds=0,
            created_at=now
        )
    
    def append_wave_data(self, field_name: str, new_data: dict) -> None:
        """追加波段数据到现有JSON字段
        
        Args:
            field_name: 字段名称
            new_data: 新的波段数据
        """
        if hasattr(self, field_name):
            current_data_str = getattr(self, field_name)
            
            # 解析现有数据
            if current_data_str:
                try:
                    current_data = json.loads(current_data_str)
                except (json.JSONDecodeError, TypeError):
                    current_data = {}
            else:
                current_data = {}
            
            # 如果是第一次添加数据，初始化结构
            if not current_data:
                current_data = {
                    "frame_rate": new_data.get("frame_rate", 250),  # 默认采样率
                    "wave": {"frames": []},
                    "filtered": {"frames": []}
                }
            
            # 追加新的frames数据
            if "wave" in new_data and "frames" in new_data["wave"]:
                current_data["wave"]["frames"].extend(new_data["wave"]["frames"])
            
            if "filtered" in new_data and "frames" in new_data["filtered"]:
                current_data["filtered"]["frames"].extend(new_data["filtered"]["frames"])
            
            # 更新frame_rate（如果提供）
            if "frame_rate" in new_data:
                current_data["frame_rate"] = new_data["frame_rate"]
            
            # 将数据转换为JSON字符串存储
            setattr(self, field_name, json.dumps(current_data))
    
    def get_wave_data(self, field_name: str) -> dict:
        """获取波段数据
        
        Args:
            field_name: 字段名称
            
        Returns:
            dict: 波段数据字典
        """
        if hasattr(self, field_name):
            data_str = getattr(self, field_name)
            if data_str:
                try:
                    return json.loads(data_str)
                except (json.JSONDecodeError, TypeError):
                    return {}
            return {}
        return {}
    
    def update_session_duration(self, end_timestamp: float) -> None:
        """更新会话时长
        
        Args:
            end_timestamp: 结束时间戳
        """
        if self.start_time:
            start_timestamp = self.start_time.timestamp()
            self.total_seconds = int(end_timestamp - start_timestamp)
            self.end_time = datetime.fromtimestamp(end_timestamp)
    
    def to_dict(self) -> dict:
        """转换为字典格式
        
        Returns:
            dict: 模型数据字典
        """
        # 处理datetime字段，确保它们是datetime对象
        start_time_str = None
        if self.start_time:
            if isinstance(self.start_time, datetime):
                start_time_str = self.start_time.isoformat()
            else:
                start_time_str = str(self.start_time)
        
        end_time_str = None
        if self.end_time:
            if isinstance(self.end_time, datetime):
                end_time_str = self.end_time.isoformat()
            else:
                end_time_str = str(self.end_time)
        
        updated_at_str = None
        if self.updated_at:
            if isinstance(self.updated_at, datetime):
                updated_at_str = self.updated_at.isoformat()
            else:
                updated_at_str = str(self.updated_at)
        
        return {
            'id': self.id,
            'room_id': self.room_id,
            'user_id': self.user_id,
            'start_time': start_time_str,
            'end_time': end_time_str,
            'total_seconds': self.total_seconds,
            'updated_at': updated_at_str
        }